package com.xhsj.user.hr.system.service;

import com.xhsj.user.hr.process.hrLeaveProcess.query.CompensatoryLeaveTimeQuery;
import com.xhsj.user.hr.process.hrLeaveProcess.vo.LeaveUsableLengthVo;
import com.xhsj.user.hr.process.overtime.mapper.TbHrOvertimeApplyMapper;
import com.xhsj.user.hr.system.entity.TbHrLeaveSetting;
import com.xhsj.user.hr.system.entity.TbHrLeaveUsableLength;
import com.xhsj.user.hr.system.mapper.TbHrLeaveUsableLengthMapper;
import com.xhsj.user.hr.system.service.TbHrLeaveUsableLengthService;
import com.xhsj.user.hr.base.BaseService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xhsj.user.utils.UserUtils;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.io.Serializable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 加班/年假 可用时长 服务实现类
 * </p>
 *
 * @author suxiaolin
 * @since Oct 27, 2020 9:47:28 AM
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
//@CacheConfig(cacheNames = "TbHrLeaveUsableLength")
public class TbHrLeaveUsableLengthService extends BaseService<TbHrLeaveUsableLengthMapper, TbHrLeaveUsableLength> {
    @Autowired
    private TbHrLeaveUsableLengthMapper dao;

    @Autowired
    private TbHrLeaveUsableLengthService tbHrLeaveUsableLengthService;

    @Autowired
    private TbHrLeaveSettingService tbHrLeaveSettingService;

    @Autowired
    private TbHrOvertimeApplyMapper tbHrOvertimeApplyMapper;


    /**
     * 保存
     *
     * @author suxiaolin
     * @date Oct 27, 2020 9:47:28 AM
     */
    @Override
    //@CacheEvict(cacheNames="TbHrLeaveUsableLength", allEntries=true)
    public boolean save(TbHrLeaveUsableLength entity) {
        return super.save(entity);
    }

    /**
     * 通过id获取数据
     *
     * @author suxiaolin
     * @date Oct 27, 2020 9:47:28 AM
     */
    @Override
    //@Cacheable(key = "#id",sync = true)
    public TbHrLeaveUsableLength getById(Serializable id) {
        return super.getById(id);
    }

    /**
     * 通过id删除数据
     *
     * @author suxiaolin
     * @date Oct 27, 2020 9:47:28 AM
     */
    @Override
    //@CacheEvict(cacheNames="TbHrLeaveUsableLength", allEntries=true)
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

    /**
     * 批量删除数据
     *
     * @author suxiaolin
     * @date Oct 27, 2020 9:47:28 AM
     */
    //@CacheEvict(cacheNames="SysDict", allEntries=true)
    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        return super.removeByIds(idList);
    }

    /**
     * 分页查询数据
     *
     * @author suxiaolin
     * @date Oct 27, 2020 9:47:28 AM
     */
    //@Cacheable(key = "#data",sync = true)
    public IPage<TbHrLeaveUsableLength> selectPage(Map<String, Object> data) {
        int currentPage = 1;
        if (!Objects.isNull(data.get("page"))) {
            currentPage = (Integer) data.get("page");
        }
        int pageSize = 20;
        if (!Objects.isNull(data.get("size"))) {
            pageSize = (Integer) data.get("size");
        }

        TbHrLeaveUsableLength entity = JSON.parseObject(JSON.toJSONString(data), TbHrLeaveUsableLength.class);
        Page<TbHrLeaveUsableLength> page = new Page(currentPage, pageSize);
        QueryWrapper<TbHrLeaveUsableLength> wrapper = new QueryWrapper(entity);
        return super.selectPage(page, wrapper);
    }

    /**
     * 查询所有数据
     *
     * @author suxiaolin
     * @date Oct 27, 2020 9:47:28 AM
     */
    @Override
    //@Cacheable(value = "TbHrLeaveUsableLength",sync = true)
    public List<TbHrLeaveUsableLength> selectAll() {
        return super.selectAll();
    }


    /**
     * 通过年份和创建人查询数据
     *
     * @author 苏小林
     * @date 2020/10/27 16:30
     * @param: currentYear
     * @param: createBy
     * @return: com.xhsj.user.hr.system.entity.TbHrLeaveUsableLength
     */
    public int getByUserIdAndYear(String currentYear, Long createBy) {
        return dao.getByUserIdAndYear(currentYear, createBy);
    }


    /**
     * 获取用户可用调休加班数
     * @author 苏小林
     * @date 2020/10/28 10:01
     * @param: createBy
     */
    public CompensatoryLeaveTimeQuery getOverTimeUsableLength(Long createBy,LocalDate now) throws ParseException {

        // 1 查询出过期时间设置
        List<TbHrLeaveSetting> tbHrLeaveSettings = tbHrLeaveSettingService.selectAll();
        TbHrLeaveSetting tbHrLeaveSetting = tbHrLeaveSettings.get(0);
        String overTimeExpireDate = tbHrLeaveSetting.getOverTimeExpireDate();
        // 本年份
        int currentYear = now.getYear();
        String str = currentYear + "-" + overTimeExpireDate;
        //指定转换格式
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 本年度截止日期
        LocalDate date = LocalDate.parse(str, fmt);

        int totalUsable = 0;
        int total = 0;
        int annualLeaveUsable = 0;

        // 查询出本年度加班可用数和去年加班可用数
        LeaveUsableLengthVo currentLeaveTimeQuery = dao.getNumberByUserIdAndYear(String.valueOf(currentYear), createBy);
        if (currentLeaveTimeQuery == null) {
            TbHrLeaveUsableLength tbHrLeaveUsableLength = new TbHrLeaveUsableLength();
            tbHrLeaveUsableLength.setYear(String.valueOf(currentYear));
            tbHrLeaveUsableLength.setAllOverTime(0);
            tbHrLeaveUsableLength.setOverTimeUsable(0);
            tbHrLeaveUsableLength.setAnnualLeaveUsable(0);
            tbHrLeaveUsableLengthService.save(tbHrLeaveUsableLength);

        }
        LeaveUsableLengthVo nextLeaveTimeQuery = dao.getNumberByUserIdAndYear(String.valueOf(currentYear-1), createBy);
        if (nextLeaveTimeQuery == null) {
            TbHrLeaveUsableLength tbHrLeaveUsableLength = new TbHrLeaveUsableLength();
            tbHrLeaveUsableLength.setYear(String.valueOf(currentYear - 1));
            tbHrLeaveUsableLength.setAllOverTime(0);
            tbHrLeaveUsableLength.setOverTimeUsable(0);
            tbHrLeaveUsableLength.setAnnualLeaveUsable(0);
            tbHrLeaveUsableLengthService.save(tbHrLeaveUsableLength);
        }

        CompensatoryLeaveTimeQuery compensatoryLeaveTimeQuery = new CompensatoryLeaveTimeQuery();

        // 过期时间

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        // 3 如果当前
        if (now.isBefore(date) || date.equals(now)) {
            // 截止日期
            Date parse = simpleDateFormat.parse(currentYear + "-" + overTimeExpireDate);
            // 当前日期
            Date parse1 = simpleDateFormat.parse(simpleDateFormat.format(new Date()));
            // 当前日期小于截止日期
//            if (parse1.getTime() <= parse.getTime()) {

                
                int surplusTime = currentLeaveTimeQuery == null?0:currentLeaveTimeQuery.getOverTimeUsable();
                int surplusTime1 = nextLeaveTimeQuery == null?0:nextLeaveTimeQuery.getOverTimeUsable();

                // 本年度年假和去年年假
                int annualLeaveUsable1 = currentLeaveTimeQuery == null?0:currentLeaveTimeQuery.getAnnualLeaveUsable();
                int annualLeaveUsable2 = nextLeaveTimeQuery == null?0:nextLeaveTimeQuery.getAnnualLeaveUsable();
                annualLeaveUsable = annualLeaveUsable1 + annualLeaveUsable2;

                compensatoryLeaveTimeQuery.setPreUsable(String.valueOf(surplusTime1));

                int hrOvertime = currentLeaveTimeQuery == null?0:currentLeaveTimeQuery.getAllOverTime();
                int hrOvertime1 = nextLeaveTimeQuery == null?0:nextLeaveTimeQuery.getAllOverTime();

                totalUsable = surplusTime+surplusTime1;
                total = hrOvertime+hrOvertime1;

//            }
        } else {
            // 查询出本年度加班可用数
            LeaveUsableLengthVo compensatoryLeaveTimeQuery1 = dao.getNumberByUserIdAndYear(String.valueOf(currentYear), createBy);
            if (compensatoryLeaveTimeQuery1 != null) {
                totalUsable = compensatoryLeaveTimeQuery1.getOverTimeUsable();
                total = compensatoryLeaveTimeQuery1.getAllOverTime();
                annualLeaveUsable = compensatoryLeaveTimeQuery1.getAnnualLeaveUsable();
            }
            compensatoryLeaveTimeQuery.setPreUsable("0");

        }


        compensatoryLeaveTimeQuery.setHrOvertime(total);
        compensatoryLeaveTimeQuery.setEndDate(simpleDateFormat.format(simpleDateFormat.parse(LocalDate.now().getYear()+1 + "-" + overTimeExpireDate)));
        compensatoryLeaveTimeQuery.setPreYear(String.valueOf(LocalDate.now().getYear() -1));
        compensatoryLeaveTimeQuery.setSurplusTime(totalUsable);
        compensatoryLeaveTimeQuery.setAnnualLeaveUsable(annualLeaveUsable);


        if (totalUsable <= 0) {
            String format = String.format("截止到目前，该员工一共加班数:%s小时，本次调休后剩余可用小时数：%s小时。", total,totalUsable);
            String format1 = String.format("截止到目前，该员工一共加班数:%s小时，剩余可用小时数：%s小时。", total,totalUsable);
            compensatoryLeaveTimeQuery.setAuditRemarks(format);
            compensatoryLeaveTimeQuery.setApplyRemarks(format1+"请尽快提交加班申请。");
        } else {
            String format = String.format("截止到目前，该员工一共加班数:%s小时，本次调休后剩余可用小时数：%s小时。", total,totalUsable);
            String format1 = String.format("截止到目前，该员工一共加班数:%s小时，剩余可用小时数：%s小时。", total,totalUsable);
            compensatoryLeaveTimeQuery.setAuditRemarks(format);
            compensatoryLeaveTimeQuery.setApplyRemarks(format1);
        }
        return compensatoryLeaveTimeQuery;
    }
}
